package controller

import (
	"api/app/wms/auto/v1/api"
	"api/app/wms/models"
	"fmt"
	"gitee.com/dreamwood/ez"
	"gitee.com/dreamwood/ez/server"
)

type ItemAttributeController struct {
	api.ItemAttributeApi
}

func init() {

	c := &ItemAttributeController{}
	c.Prepare()
	c.AddRoute("/list", c.ListAction)
	c.AddRoute("/get", c.GetAction)
	c.AddRoute("/scan", c.ScanAction)
	c.AddRoute("/choice", c.ChoiceAction)
	c.AddRoute("/save", c.SaveAction)
	c.AddRoute(`/save_many`, c.SaveManyAction)
	c.AddRoute("/delete", c.DeleteAction)
	c.AddRoute("/delete_many", c.DeleteManyAction)
	c.AddRoute("/copy", c.CopyAction)
	c.AddRoute("/gen_value", c.GenerateValuesAction)
}

//如果不满意自动生成的方法，请自定义，本文件不会被生成器覆盖，请放心操作
//func (this *ItemAttributeController) SaveAction(operation *server.Operation) {}
//func (this *ItemAttributeController) GetAction(operation *server.Operation) {}
//func (this *ItemAttributeController) ScanAction(operation *server.Operation) {}
//func (this *ItemAttributeController) ListAction(operation *server.Operation) {}
//func (this *ItemAttributeController) DeleteAction(operation *server.Operation) {}

func (c *ItemAttributeController) GenerateValuesAction(operation *server.Operation) {
	this := c.TakeOver(operation)
	id := this.Get("id").IsInt()
	crud := models.NewItemAttributeCrud()
	//crud.Factory.SetAssociations("Attribute", "Attribute.Values")
	itemAttr, e := crud.Find(id)
	if this.CheckError(e) {
		return
	}
	crudV := models.NewAttributeValueCrud()
	values, e := crudV.FindBy(ez.M{
		"kId":            itemAttr.AttributeId,
		"itemBaseId__in": []int{itemAttr.ItemBaseId, 0},
		"isOn":           true,
	}, []string{"sort"}, 0, 0)
	ks := make([]string, 0)
	vs := make([]string, 0)
	kvStr := ""
	for _, value := range values {
		ks = append(ks, value.Code)
		vs = append(vs, value.Name)
		kvStr += fmt.Sprintf("[%s]", value.Code)
		kvStr += fmt.Sprintf("[%s]", value.Name)
	}
	itemAttr.Values = kvStr
	itemAttr.Save(false)
	this.ReturnSuccess("OK", itemAttr)
}
